Lists

In this lesson, we will learn about an important data structure in Python: lists.

A data structure is a way of storing and organizing data according to a certain format or structure. Data structures are a crucial part of computer programming. Since we frequently deal with data manipulation, it is of paramount importance to organize it in an efficient and meaningful way.

The three commonly used built-in data structures offered in Python 3 are:

  1. List
  2. Tuple
  3. Dictionary

List#

List allows us to store elements of different data types in one container. The contents of a list are enclosed by square brackets, [].

Lists are ordered and elements are stored linearly at specific indexes.

svg viewer

Creating#

Here’s an example of lists inside another list:

Merging#

Python makes it really easy to merge lists together. The simplest way is to use the + operator or the extend() function:

Appending#

The append() function appends the input argument at the end of the list.

list.append(value)

List Comprehension#

List comprehension is a technique that uses a for loop and a condition to create a new list from an existing one.

A list comprehension statement is always enclosed in square brackets, []. Let’s see how list comprehension makes our task easier:

List comprehension can also be performed on more than one list. The number of for loops in the comprehension will correspond to the number of lists we’re using.

Below is an example of creating a list of lists using two for loops:

Now let’s perform the same task using list comprehension:


In the next lesson, we will learn about tuples and dictionaries.

Lambdas

Tuples and Dictionaries